//
//  MyGolfVipController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/27.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import JDFTooltips

fileprivate class GolfDateModel: NSObject {
    var date:String = ""
    var isSelect:Bool = false
}

fileprivate class GolfAreaModel: NSObject {
    var id:String = ""
    var name:String = ""
    var status:String = ""
    var remark:String = ""
}

fileprivate class GolfTimeModel: NSObject {
    var time:String = ""
    var isSelect:Bool = false
}

fileprivate class GolfSelectButton: UIButton {
    
    var isGolfSelected: Bool = false {
        didSet {
            self.setTitleColor(UIColor(hex: isGolfSelected ? 0xffffff : 0x333333), for: .normal)
            self.backgroundColor = UIColor(hex: isGolfSelected ? 0xff5722 : 0xffffff)
            self.borderWidth = isGolfSelected ? 0.0 : 1.0
        }
    }
    
    var isGolfEnable: Bool = true {
        didSet {
            self.isGolfSelected = false
            
            self.setTitleColor(UIColor(hex: isGolfEnable ? 0x333333 : 0xcccccc), for: .normal)
            self.borderColor = UIColor(hex: isGolfEnable ? 0xbfbfbf : 0xe5e5e5)
        }
    }
    
    //主键标识
    var key:String = ""
    //备注
    var remark:String = ""
    
    init(title:String, key:String) {
        super.init(frame: .zero)
        self.key = key
        
        self.setTitle(title, for: .normal)
        self.setTitleColor(UIColor(hex:0x333333), for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: 13.wr)
        self.cb_size = CGSize(width: 100.wr, height: 29.hr)
        self.borderColor = UIColor(hex:0xbfbfbf)
        self.cornerRadius = 2
        self.borderWidth = 1
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class MyGolfVipController: CBBaseViewController {
    
    @IBOutlet weak var lblProductName: UILabel!
    
    @IBOutlet weak var lblPrice: UILabel!
    
    @IBOutlet weak var lblAddress: UILabel!
    
    @IBOutlet weak var lblBeginTime: UILabel!
    
    @IBOutlet weak var vwReserve: UIView!
    
    @IBOutlet weak var btnReserve: UIButton!
    
    fileprivate var arrDateButton:[GolfSelectButton] = [GolfSelectButton]()
    fileprivate var arrAreaButton:[GolfSelectButton] = [GolfSelectButton]()
    fileprivate var arrTimeButton:[GolfSelectButton] = [GolfSelectButton]()
    
    fileprivate var selectDate:Variable<GolfSelectButton?> = Variable(nil)
    fileprivate var selectArea:Variable<GolfSelectButton?> = Variable(nil)
    fileprivate var selectTime:Variable<GolfSelectButton?> = Variable(nil)
    
    var vipInfoModel:GolfVipInfoModel!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的高尔夫"
        
        lblProductName.text = vipInfoModel.name
        lblPrice.text = vipInfoModel.price
        lblAddress.text = vipInfoModel.address
        lblBeginTime.text = vipInfoModel.start_time + "(有效期:1年)"
        
        setupData()
        
        let combinInput = Observable.combineLatest(selectDate.asObservable(), selectArea.asObservable(), selectTime.asObservable()) { return (date:$0, area:$1, time:$2) }.share(replay:1)
        
        combinInput.map { (input) -> Bool in
            return (input.date != nil) && (input.area != nil) && (input.time != nil)
            }.subscribe(onNext:{ [unowned self] isValid in
                self.btnReserve.isEnabled = isValid
                self.btnReserve.alpha = isValid ? 1.0 : 0.5
            }).disposed(by: disposeBag)
        
        btnReserve.rx.tap.asObservable()
            .withLatestFrom(combinInput)
            .flatMapLatest { (input) -> Observable<Bool> in
                SVProgressHUD.show()
                return NetworkTool.requestData(url: ActionURL.GOLF_RESERVE_VIP, param: [
                        "uid":MainTools.shared.userModel?.uid ?? "",
                        "date":input.date?.key ?? "",
                        "golf_id":input.area?.key ?? "",
                        "time":input.time?.key ?? "",
                    ])
                    .map({ (json) -> Bool in
                        return true
                    }).catchErrorJustReturn(false)
            }.subscribe(onNext: { [unowned self] isSuccess in
                if isSuccess {
                    MainTools.makeToast(message: "预约成功")
                    self.clearSelect(type: 0)
                    self.clearSelect(type: 1)
                    self.clearSelect(type: 2)
                }
                SVProgressHUD.dismiss()
            }).disposed(by: disposeBag)
        
        let tap = UITapGestureRecognizer()
        tap.rx.event.subscribe(onNext:{ [weak self] _ in
            self?.lastToolTips?.removeFromSuperview()
        }).disposed(by: disposeBag)
        self.view.addGestureRecognizer(tap)
    }
    
    func setupData() {
        let arrDate = [0,  24 * 60 * 60,  24 * 60 * 60 * 2]
        self.arrDateButton = arrDate.enumerated().map({ (index, offset) -> GolfSelectButton in
            let strDate = Date(timeIntervalSinceNow: TimeInterval(offset)).normalString
            let tempButton = GolfSelectButton(title: strDate, key: strDate)
            tempButton.tag = index
            return tempButton
        })
        
        let arrTime = ["09:00", "11:00", "13:00", "15:00", "17:00", "19:00"]
        self.arrTimeButton = arrTime.enumerated().map({ (index, time) -> GolfSelectButton in
            let tempButton = GolfSelectButton(title: time, key: time)
            tempButton.tag = index
            return tempButton
        })
        
        
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_GOLF_VIP_AREA, param: ["type":"0","uid":MainTools.shared.userModel?.uid ?? ""])
            .map { (json) -> [GolfAreaModel]? in
                return GolfAreaModel.mj_objectArray(withKeyValuesArray: json["rows"].dictionaryValue["data"]?.arrayObject) as? [GolfAreaModel]
            }.catchErrorJustReturn(nil)
            .subscribe(onNext:{ [unowned self] opArr in
                if let tempArr = opArr {
                    self.arrAreaButton = tempArr.enumerated().map({ (index, model) -> GolfSelectButton in
                        let tempButton = GolfSelectButton(title: model.name, key: model.id)
                        tempButton.remark = model.remark
                        tempButton.tag = index
                        tempButton.isGolfEnable = model.status == "0"
                        return tempButton
                    })
                    self.setupReserveView()
                }
                SVProgressHUD.dismiss()
            }).disposed(by: disposeBag)
        
    }
    
    override func setupRightBtnAction() {
        self.view.endEditing(true)
        let btnDetail = UIButton(text: "我的预约", color: .white, fontSize: 15.wr)
        btnDetail.cb_size = CGSize(width: 30, height: 30)
        btnDetail.rx.tap
            .subscribe(onNext:{ [weak self] _ in
                let reserveVc = MyGolfReserveController()
                self?.navigationController?.pushViewController(reserveVc, animated: true)
            }).disposed(by: disposeBag)
        let rightBarButtonItem:UIBarButtonItem =
            UIBarButtonItem(customView: btnDetail)
        rightBarButtonItem.tintColor = .white
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    
    func setupReserveView() {
        let lblT1 = UILabel(text: "选择日期:", color: .black, fontSize: 14.wr, isBold: false)
        lblT1.cb_left = 22.wr
        lblT1.cb_top = 15.hr
        vwReserve.addSubview(lblT1)
        var lastTmpLastHt = self.setRows(type: 0, lastHt: lblT1.cb_bottom + 12.hr)
        
        let lblT2 = UILabel(text: "选择场地:", color: .black, fontSize: 14.wr, isBold: false)
        lblT2.cb_top = lastTmpLastHt
        lblT2.cb_left = 22.wr
        vwReserve.addSubview(lblT2)
        lastTmpLastHt = self.setRows(type: 1, lastHt: lblT2.cb_bottom + 12.hr)

        let lblT3 = UILabel(text: "入场时间:", color: .black, fontSize: 14.wr, isBold: false)
        lblT3.cb_left = 22.wr
        lblT3.cb_top = lastTmpLastHt
        vwReserve.addSubview(lblT3)
        lastTmpLastHt = self.setRows(type: 2, lastHt: lblT3.cb_bottom + 12.hr)

        vwReserve.snp.updateConstraints { (make) in
            make.height.equalTo(lastTmpLastHt)
        }
        
    }
    
    //type 0 选择日期 1 选择场地 2 入场时间
    fileprivate func setRows(type:Int, lastHt:CGFloat) -> CGFloat {
        var lastTmpLastHt = lastHt
        var tmpArrButton:[GolfSelectButton] = arrDateButton
        var selector:Selector = #selector(selectDate(btn:))
        switch type {
        case 0:
            tmpArrButton = arrDateButton
            selector = #selector(selectDate(btn:))
            break
        case 1:
            tmpArrButton = arrAreaButton
            selector = #selector(selectArea(btn:))
            break
        case 2:
            tmpArrButton = arrTimeButton
            selector = #selector(selectTime(btn:))
            break
        default: break
        }
        let allRow = Int(ceil(Double(tmpArrButton.count) / 3.0)) - 1
        let lastRowCount = tmpArrButton.count % 3
        for i in 0...allRow {
            if i < allRow || lastRowCount == 0 {
                vwReserve.cb_addSubView(arrSub: ["~",tmpArrButton[i*3],19,tmpArrButton[i*3+1],19,tmpArrButton[i*3+2],"~"], viewLayout: .CBViewTop, originValue: lastTmpLastHt)
                tmpArrButton[i*3].addTarget(self, action: selector, for: .touchUpInside)
                tmpArrButton[i*3+1].addTarget(self, action: selector, for: .touchUpInside)
                tmpArrButton[i*3+2].addTarget(self, action: selector, for: .touchUpInside)
                lastTmpLastHt = tmpArrButton[i*3].cb_bottom + 13.hr
            } else {
                for j in 0..<lastRowCount {
                    tmpArrButton[i*3+j].cb_left = (arrDateButton.first?.left ?? 0) + j.cg*119.wr
                    tmpArrButton[i*3+j].cb_top = lastTmpLastHt
                    vwReserve.addSubview(tmpArrButton[i*3+j])
                    tmpArrButton[i*3+j].addTarget(self, action: selector, for: .touchUpInside)
                }
                lastTmpLastHt = tmpArrButton[i*3].cb_bottom + 17.hr
            }
        }
        return lastTmpLastHt
    }
    
    @objc fileprivate func selectDate(btn:GolfSelectButton) {
        self.lastToolTips?.removeFromSuperview()
        if !btn.isGolfEnable {
            return
        }
        if let lastSelectBtn = (arrDateButton.filter { $0.isGolfSelected }).first {
            if btn == lastSelectBtn {
                return
            }
            lastSelectBtn.isGolfSelected = false
        }
        btn.isGolfSelected = true
        selectDate.value = btn
        queryTimeInfoByDateAndArea()
    }
    
    var lastToolTips:JDFTooltipView?
    @objc fileprivate func selectArea(btn:GolfSelectButton) {
        lastToolTips?.removeFromSuperview()
        if !btn.isGolfEnable {
            let tooltip = JDFTooltipView.init(targetView: btn, hostView: self.view, tooltipText: btn.remark, arrowDirection: .down, width: 100.wr)
            tooltip?.show()
            lastToolTips = tooltip
            return
        }
        if let lastSelectBtn = (arrAreaButton.filter { $0.isGolfSelected }).first {
            if btn == lastSelectBtn {
                return
            }
            lastSelectBtn.isGolfSelected = false
        }
        btn.isGolfSelected = true
        selectArea.value = btn
        queryTimeInfoByDateAndArea()
    }
    
    @objc fileprivate func selectTime(btn:GolfSelectButton) {
        self.lastToolTips?.removeFromSuperview()
        if !btn.isGolfEnable {
            return
        }
        if let lastSelectBtn = (arrTimeButton.filter { $0.isGolfSelected }).first {
            if btn == lastSelectBtn {
                return
            }
            lastSelectBtn.isGolfSelected = false
        }
        btn.isGolfSelected = true
        selectTime.value = btn
    }
    
    //type 0 选择日期 1 选择场地 2 入场时间
    func clearSelect(type:Int) {
        switch type {
        case 0:
            for btn in arrDateButton {
                btn.isGolfSelected = false
            }
            break
        case 1:
            for btn in arrAreaButton {
                if btn.isGolfEnable {
                    btn.isGolfSelected = false
                }
            }
            break
        case 2:
            for btn in arrTimeButton {
                btn.isGolfEnable = true
            }
            break
        default: break
        }
    }
    
    func queryTimeInfoByDateAndArea() {
        //必须选择了日期和场地，才能查询时间
        if selectDate.value == nil || selectArea.value == nil {
            return
        }
        clearSelect(type: 2)
        
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_GOLF_VIP_RESERVE_TIME, param: ["date":selectDate.value?.key ?? "", "golf_id":selectArea.value?.key ?? "", "uid":MainTools.shared.userModel?.uid ?? ""])
            .map { (json) -> [String]? in
                return json["rows"].dictionaryValue["data"]?.arrayValue.map { $0["time"].stringValue }
            }.catchErrorJustReturn(nil)
            .subscribe(onNext: { filterTimeOpArr in
                if let filterArr = filterTimeOpArr {
                    let unEnableTimeBtns = self.arrTimeButton.filter { return filterArr.contains($0.key) }
                    for btn in unEnableTimeBtns {
                        btn.isGolfEnable = false
                    }
                }
                SVProgressHUD.dismiss()
            }).disposed(by: disposeBag)
        
    }
    

}
